package cn.ultrarisk.scadmin.manager.biz.solr.dao;

import cn.ultrarisk.mybatis.extension.domain.Page;
import cn.ultrarisk.mybatis.extension.query.Query;
import cn.ultrarisk.scadmin.manager.biz.solr.entity.SolrNode;
import cn.ultrarisk.scadmin.manager.biz.solr.entity.SolrReplica;
import cn.ultrarisk.scadmin.manager.support.BaseDAO;
import cn.ultrarisk.scadmin.manager.util.CollectionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.*;

/**
 * solr节点数据操作类
 *
 * @author sevendlong(lin23871@163.com)
 * @date 2014/3/28
 * @since V1.0
 */
@Repository
public class SolrNodeDAO extends BaseDAO<SolrNode, Integer> {
    @Autowired
    private SolrReplicaDAO solrReplicaDAO;

    /**
     * 构造器
     */
    public SolrNodeDAO() {
        super(SolrNode.class, SolrNode.COLUMN_PROPERTY_MAP);
    }

    public Map<Integer, String> getNameMap(Collection<Integer> ids) {
        Map<Integer, String> nameMap = new HashMap<Integer, String>();
        if (CollectionUtil.isNotEmpty(ids)) {
            List<SolrNode> nodes = findByIds(ids, SolrNode.ID, SolrNode.NAME);
            if (CollectionUtil.isNotEmpty(nodes)) {
                for (SolrNode node : nodes) {
                    nameMap.put(node.getId(), node.getName());
                }
            }
        }
        return nameMap;
    }

    public List<SolrNode> findAvailable(Integer collectionId) {
        List<Integer> nodeIds = null;
        if (collectionId != null) {
            Query query = Query.query(SolrReplica.COLLECTION_ID, collectionId);
            query.addGroup(SolrReplica.NODE_ID);
            nodeIds = solrReplicaDAO.findColumn(query, SolrReplica.NODE_ID, true, true);
            if (CollectionUtil.isEmpty(nodeIds)) {
                return new ArrayList<SolrNode>();
            }
        }
        Query query = Query.query(SolrNode.AVAILABLE, true).in(SolrNode.ID, nodeIds);
        query.addSort(SolrNode.NAME, Query.Direction.ASC);
        return findList(query);
    }

    public Page<SolrNode> findPage(String host, Boolean available, String solrVersion, int pageNo, int pageSize) {
        Query query = Query.query(SolrNode.HOST, host).eq(SolrNode.AVAILABLE, available).eq(SolrNode.SOLR_SPEC_VERSION, solrVersion);
        query.addSort(SolrNode.NAME, Query.Direction.ASC);
        return findPage(query, pageNo, pageSize);
    }
}
